package org.ds.blog.service.impl;

import org.ds.blog.mapper.ArticleMapper;
import org.ds.blog.model.Article;
import org.ds.blog.service.ArticleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.List;

@Service("articleService")
@Transactional
public class ArticleServiceImpl implements ArticleService {

    @Resource
    ArticleMapper articleMapper;

    @Override
    public Article getArticleById(Integer articleId) {
      return articleMapper.getArticleById(articleId);
    }

    @Override
    public List<Article> getArticleByState(Integer state, Integer userId, String title) {
        return articleMapper.getArticleByState(state,userId,title);
    }

    @Override
    public Integer addArticle(Article article) {
        if(article.getId()==-1){
            //设置发布日期
            article.setPublishDate(new Timestamp(System.currentTimeMillis()));
            int i=articleMapper.addArticle(article);
            //将新增的标签放入数据库
            String[] tags=article.getTags();
            if(tags!=null&&tags.length>0) {
                int tag = addTagsToArticle(tags, article.getId());
                if (tag == -1) {
                    return tag;
                }
            }
            return i;
        }else {
            article.setPublishDate(new Timestamp(System.currentTimeMillis()));
            int i=articleMapper.updateArticle(article);
            String[] tags=article.getTags();
            if(tags!=null&&tags.length>0) {
                int tag = addTagsToArticle(tags, article.getId());
                if (tag == -1) {
                    return tag;
                }
            }
            return i;
        }
    }

    @Override
    public Integer addTagsToArticle(String[] tags, Integer articleId) {
        //首先删除关于文章的所有标签
        articleMapper.deleteTagsByArticleId(articleId);
        //将新标签放入数据库
        articleMapper.addTags(tags);
        //从数据库中读取ID
        List<Integer> tagIds=articleMapper.getTagIdsByTagNames(tags);
        //将新标签与文章关系存储
        int i=articleMapper.addTagIdsAndArticleId(tagIds,articleId);
        return i == tags.length ? i : -1;
    }

    @Override
    public Integer restoreArticleById(Integer articleId) {
        return articleMapper.updateArticleStateById(articleId,1);
    }

    /**
     *
     * @param articleIds 传入文章ID数组批量删除
     * @param state 决定彻底删除还是放入回收站
     * @return 返回删除结果
     */
    @Override
    public Integer deleteArticlesByState(Integer []articleIds,Integer state) {
        if(state==2){
            return articleMapper.deleteArticle(articleIds);
        }else {
            return articleMapper.updateArticleState(articleIds,2);
        }
    }
}
